package com.kancy.springcloudconfig.util.service;

import com.kancy.springcloudconfig.util.Base64Util;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;

/**
 * 加解密服务
 *
 * @author dongzhuming
 */
public class CryptoService {

    private final CipherHolder cipherHolder;

    public CryptoService(CipherHolder cipherHolder) {
        this.cipherHolder = cipherHolder;
    }

    public byte[] encrypt(byte[] dataToEncrypt) {
        if (dataToEncrypt == null || dataToEncrypt.length == 0) {
            return dataToEncrypt;
        }
        Cipher cipher = cipherHolder.getEncryptionCipher();
        try {
            return cipher.doFinal(dataToEncrypt);
        } catch (BadPaddingException | IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        }
    }

    public String encryptAndEncode(byte[] dataToEncrypt) {
        byte[] encryptedData = encrypt(dataToEncrypt);
        return Base64Util.encodeBytes(encryptedData);
    }

    public byte[] encryptString(String dataToEncrypt) {
        if (dataToEncrypt == null) {
            return new byte[0];
        }
        return encrypt(dataToEncrypt.getBytes());
    }

    public byte[] decrypt(byte[] encryptedData) {
        if (encryptedData == null || encryptedData.length == 0) {
            return encryptedData;
        }
        try {
            final Cipher cipher = cipherHolder.getDecryptionCipher();
            return cipher.doFinal(encryptedData);
        } catch (BadPaddingException | IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        }
    }

    public byte[] decodeAndDecrypt(String encryptedData) {
        if (encryptedData == null) {
            return new byte[0];
        }
        if (encryptedData.length() == 0) {
            return new byte[0];
        }
        byte[] encryptedBytes = Base64Util.decodeString(encryptedData);
        return decrypt(encryptedBytes);
    }

    public String decryptString(byte[] encryptedData) {
        if (encryptedData == null) {
            return null;
        }
        return new String(decrypt(encryptedData));
    }
}
